package com.yhsoft.mall.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yhsoft.common.service.TokenService;
import com.yhsoft.mall.controller.request.*;
import com.yhsoft.mall.controller.response.*;
import com.yhsoft.mall.entity.ModuleInfo;
import com.yhsoft.mall.entity.TopicInfo;
import com.yhsoft.mall.mapper.ModuleInfoMapper;
import com.yhsoft.mall.mapper.TopicInfoMapper;
import com.yhsoft.mall.service.IModuleInfoService;
import com.yhsoft.mall.service.ITopicInfoService;
import com.yhsoft.mall.util.Constants;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商城专题信息表 服务实现类
 * </p>
 *
 * @author yyyyyyyh
 * @since 2023-10-12
 */
@Service
public class TopicInfoServiceImpl extends ServiceImpl<TopicInfoMapper, TopicInfo> implements ITopicInfoService {

    @Resource
    private ModuleInfoMapper moduleInfoMapper;

    @Resource
    private IModuleInfoService iModuleInfoService;

    @Resource
    private TopicInfoMapper topicInfoMapper;

    @Override
    public IPage<TopicListOutVo> getTopicList(TopicListInVo inVo) {
        QueryWrapper<TopicInfo> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.hasLength(inVo.getName()), "name", inVo.getName())
                .gt(inVo.getStartTime() != null, "updated_time", inVo.getStartTime())
                .lt(inVo.getEndTime() != null, "updated_time", inVo.getEndTime())
                .eq(StringUtils.hasLength(inVo.getAppId()), "app_id", inVo.getAppId())
                .eq(!StringUtils.hasLength(inVo.getAppId()), "company_id", TokenService.getUserBytoken().getCompanyId());
        IPage<TopicInfo> page = new Page<>(inVo.getPageNo(), inVo.getPageSize());
        IPage<TopicInfo> topicInfoIPage = topicInfoMapper.selectPage(page, wrapper);

        IPage<TopicListOutVo> convert = topicInfoIPage.convert(topicInfo -> {
            TopicListOutVo form = new TopicListOutVo();
            //设置商品数
            if (topicInfo.getType() == 1) {
                //通用
                TopicGeneralContentListInVo topicGeneralContentListInVo = JSONUtil.toBean(topicInfo.getContent(), TopicGeneralContentListInVo.class);
                form.setGoodsNum(topicGeneralContentListInVo.getGoodsIds() == null ? 0 : topicGeneralContentListInVo.getGoodsIds().size());
            } else {
                if (topicInfo.getContent() == null) {
                    form.setGoodsNum(0);
                } else {
                    //充值
                    List<Integer> moduleIds = Arrays.stream(topicInfo.getContent().split(","))
                            .map(Integer::parseInt).collect(Collectors.toList());
                    LambdaQueryWrapper<ModuleInfo> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.in(ModuleInfo::getId, moduleIds);
                    queryWrapper.in(ModuleInfo::getModuleName, Constants.MODULE_NAME.get(5));
                    ModuleInfo moduleInfos = moduleInfoMapper.selectOne(queryWrapper);
                    if (moduleInfos == null || !StringUtils.hasLength(moduleInfos.getContent())) {
                        form.setGoodsNum(0);
                    } else {
                        GoodsBarContentListInVo contentVo = JSONUtil.toBean(moduleInfos.getContent(), GoodsBarContentListInVo.class);
                        form.setGoodsNum(contentVo.getGoodsIds() == null ? 0 : contentVo.getGoodsIds().size());
                    }
                }
            }
            BeanUtils.copyProperties(topicInfo, form);
            return form;
        });

        return convert;
    }

    @Override
    public void addTopicInfo(TopicInfoAddInVo inVo) {
        TopicInfo topicInfo = new TopicInfo();
        BeanUtils.copyProperties(inVo, topicInfo);
        topicInfo.setCompanyId(TokenService.getUserBytoken().getCompanyId());
        topicInfo.setAppId(iModuleInfoService.getBaicInterfaceConfig(topicInfo.getCompanyId()).getAppId());

        topicInfoMapper.insert(topicInfo);
    }

    @Override
    public void deleteTopicInfo(Integer id) {
        topicInfoMapper.deleteById(id);
    }

    /**
     * 设置 通用专题 模块内容
     *
     * @param inVo
     */
    @Override
    public void setTopicGeneralBar(TopicGeneralInVo inVo) {
        TopicInfo topicInfo = new TopicInfo();
        BeanUtils.copyProperties(inVo, topicInfo);
        topicInfo.setContent(inVo.getContent().toString());
        topicInfoMapper.updateById(topicInfo);
    }

    @Override
    public TopicGeneralInVo getTopicGeneralInfo(Integer id) {
        TopicInfo topicInfo = topicInfoMapper.selectById(id);
        TopicGeneralInVo vo = new TopicGeneralInVo();
        vo.setId(topicInfo.getId());
        vo.setName(topicInfo.getName());
        vo.setRemark(topicInfo.getRemark());
        vo.setContent(JSONUtil.toBean(topicInfo.getContent(), TopicGeneralContentListInVo.class));

        return vo;

    }


    /**
     * 新增 充值中心 模块内容
     *
     * @param inVo
     */
    @Override
    @Transactional
    public void addTopUpBar(TopUpBarInVo inVo) {
        ModuleInfo moduleInfo = new ModuleInfo();
        BeanUtils.copyProperties(inVo, moduleInfo);

        moduleInfo.setId(null);
        moduleInfo.setIsTopic(1);
        moduleInfo.setTopicId(inVo.getId());
        moduleInfo.setCompanyId(TokenService.getUserBytoken().getCompanyId());
        moduleInfo.setContent(inVo.getContent().toString());
        moduleInfo.setModuleName(Constants.MODULE_NAME.get(6));
        moduleInfo.setAppId(iModuleInfoService.getBaicInterfaceConfig(moduleInfo.getCompanyId()).getAppId());

        moduleInfoMapper.insert(moduleInfo);

        //返回主键,设置专题表关联id
        Integer moduleId = moduleInfo.getId();
        TopicInfo topicInfo = topicInfoMapper.selectById(inVo.getId());
        topicInfo.setContent(StringUtils.hasLength(topicInfo.getContent()) ? topicInfo.getContent() + "," + moduleId : "" + moduleId);
        topicInfoMapper.updateById(topicInfo);
    }

    /**
     * 修改 充值中心 模块内容
     *
     * @param inVo
     */
    @Override
    public void updateTopUpBar(TopUpBarInVo inVo) {
        ModuleInfo moduleInfo = new ModuleInfo();
        BeanUtils.copyProperties(inVo, moduleInfo);
        moduleInfo.setContent(inVo.getContent().toString());
        moduleInfo.setId(inVo.getModuleId());
        moduleInfoMapper.updateById(moduleInfo);
    }

    /**
     * 新增 品牌会员 模块内容
     *
     * @param inVo
     */
    @Override
    public void addBrandBar(BrandBarInVo inVo) {
        ModuleInfo moduleInfo = new ModuleInfo();
        BeanUtils.copyProperties(inVo, moduleInfo);

        moduleInfo.setId(null);
        moduleInfo.setIsTopic(1);
        moduleInfo.setTopicId(inVo.getId());
        moduleInfo.setCompanyId(TokenService.getUserBytoken().getCompanyId());
        moduleInfo.setContent(inVo.getContent().toString());
        moduleInfo.setModuleName(Constants.MODULE_NAME.get(7));
        moduleInfo.setAppId(iModuleInfoService.getBaicInterfaceConfig(moduleInfo.getCompanyId()).getAppId());

        moduleInfoMapper.insert(moduleInfo);

        //返回主键,设置专题表关联id
        Integer moduleId = moduleInfo.getId();
        TopicInfo topicInfo = topicInfoMapper.selectById(inVo.getId());
        topicInfo.setContent(StringUtils.hasLength(topicInfo.getContent()) ? topicInfo.getContent() + "," + moduleId : "" + moduleId);
        topicInfoMapper.updateById(topicInfo);
    }

    /**
     * 修改 品牌会员 模块内容
     *
     * @param inVo
     */
    @Override
    public void updateBrandBar(BrandBarInVo inVo) {
        ModuleInfo moduleInfo = new ModuleInfo();
        BeanUtils.copyProperties(inVo, moduleInfo);
        moduleInfo.setContent(inVo.getContent().toString());
        moduleInfo.setId(inVo.getModuleId());
        moduleInfoMapper.updateById(moduleInfo);
    }


    /**
     * 新增 商品 模块内容
     *
     * @param inVo
     */
    @Override
    public void addGoodsBar(TopicGoodsBarInVo inVo) {
        ModuleInfo moduleInfo = new ModuleInfo();
        BeanUtils.copyProperties(inVo, moduleInfo);

        moduleInfo.setId(null);
        moduleInfo.setIsTopic(1);
        moduleInfo.setTopicId(inVo.getId());
        moduleInfo.setCompanyId(TokenService.getUserBytoken().getCompanyId());
        moduleInfo.setContent(inVo.getContent().toString());
        moduleInfo.setModuleName(Constants.MODULE_NAME.get(5));
        moduleInfo.setAppId(iModuleInfoService.getBaicInterfaceConfig(moduleInfo.getCompanyId()).getAppId());

        moduleInfoMapper.insert(moduleInfo);

        //返回主键,设置专题表关联id
        Integer moduleId = moduleInfo.getId();
        TopicInfo topicInfo = topicInfoMapper.selectById(inVo.getId());
        topicInfo.setContent(StringUtils.hasLength(topicInfo.getContent()) ? topicInfo.getContent() + "," + moduleId : "" + moduleId);
        topicInfoMapper.updateById(topicInfo);
    }

    /**
     * 修改 商品 模块内容
     *
     * @param inVo
     */
    @Override
    public void updateGoodsBar(TopicGoodsBarInVo inVo) {
        ModuleInfo moduleInfo = new ModuleInfo();
        BeanUtils.copyProperties(inVo, moduleInfo);
        moduleInfo.setContent(inVo.getContent().toString());
        moduleInfo.setId(inVo.getModuleId());
        moduleInfoMapper.updateById(moduleInfo);
    }


    @Override
    public TopicInfoOutVo getTopUpTopicInfo(Integer id) {
        TopicInfoOutVo outVo = new TopicInfoOutVo();

        //获取充值专题对应的模块配置id
        TopicInfo topicInfo = topicInfoMapper.selectById(id);

        // 设置空值
        if (!StringUtils.hasLength(topicInfo.getContent())) {
            outVo.setTopUpBar(new TopUpBarOutVo());
            outVo.setBrandBar(new BrandBarOutVo());
            outVo.setGoodsBar(new TopicGoodsBarOutVo());
            return outVo;
        }

        List<Integer> moduleIds = Arrays.stream(topicInfo.getContent().split(","))
                .map(Integer::parseInt).collect(Collectors.toList());


        LambdaQueryWrapper<ModuleInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ModuleInfo::getId, moduleIds);
        List<ModuleInfo> moduleInfos = moduleInfoMapper.selectList(queryWrapper);

        moduleInfos.forEach(ModuleInfo -> {

            //充值
            if (Constants.MODULE_NAME.get(6).equals(ModuleInfo.getModuleName())) {
                TopUpBarOutVo vo = new TopUpBarOutVo();
                vo.setModuleId(ModuleInfo.getId());
                vo.setIsEnable(ModuleInfo.getIsEnable());

                //jsonArray字符串转List<bean>
                List<TopUpBarContentLIstInVo> contentVo = JSONUtil.toList(ModuleInfo.getContent(), TopUpBarContentLIstInVo.class);
                vo.setContent(contentVo);
                outVo.setTopUpBar(vo);
            }
            //品牌会员
            if (Constants.MODULE_NAME.get(7).equals(ModuleInfo.getModuleName())) {
                BrandBarOutVo vo = new BrandBarOutVo();
                vo.setModuleId(ModuleInfo.getId());
                vo.setIsEnable(ModuleInfo.getIsEnable());

                //jsonArray字符串转List<bean>
                List<BrandBarContentLIstInVo> contentVo = JSONUtil.toList(ModuleInfo.getContent(), BrandBarContentLIstInVo.class);
                vo.setContent(contentVo);
                outVo.setBrandBar(vo);
            }
            //商品
            if (Constants.MODULE_NAME.get(5).equals(ModuleInfo.getModuleName())) {
                TopicGoodsBarOutVo vo = new TopicGoodsBarOutVo();
                vo.setModuleId(ModuleInfo.getId());
                vo.setIsEnable(ModuleInfo.getIsEnable());

                if (StringUtils.hasLength(ModuleInfo.getContent())) {
                    vo.setContent(new GoodsBarContentListInVo());
                } else {
                    //json字符串转bean
                    GoodsBarContentListInVo contentVo = JSONUtil.toBean(ModuleInfo.getContent(), GoodsBarContentListInVo.class);
                    vo.setContent(contentVo);
                }
                outVo.setGoodsBar(vo);
            }
        });
        return outVo;
    }

    @Override
    public boolean exists(String BarName, Integer id) {
        LambdaQueryWrapper<ModuleInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ModuleInfo::getCompanyId, TokenService.getUserBytoken().getCompanyId());
        wrapper.eq(ModuleInfo::getIsTopic, 1);
        wrapper.eq(ModuleInfo::getTopicId, id);
        wrapper.eq(ModuleInfo::getModuleName, BarName);
        return moduleInfoMapper.exists(wrapper);
    }

}
